 

package com.hs.core.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest; 
import org.apache.log4j.Logger;

/**
 * 创建日期:2007-7-18
 * Title:流程
 * Description：分页查询 
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */

public class QueryPage {
	
	/**  用来保存要传递的参数值的哈希Table  */
	private Map conditionMap = new Hashtable();
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(QueryPage.class);
	
	public QueryPage(HttpServletRequest request, String url , String sql){
		this.request = request;
		this.basePath = url;
		searchSql = sql;
		searchSql = searchSql.replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "");
		init();
	}
	
	/**谢彬新增带查询参数的分页2008.3.14
	 * @param request
	 * @param url
	 * @param sql
	 * @param condition
	 */
	public QueryPage(HttpServletRequest request, String url , String sql,Map condition){
		this.conditionMap=condition;
		this.request = request;
		this.basePath = url;
		searchSql = sql;
		searchSql = searchSql.replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "");
		init();
	}
	public QueryPage(HttpServletRequest request, String url , String sql,int perPageNum){
		this.request = request;
		this.perPageCount = perPageNum;
		this.basePath = url;
		searchSql = sql;
		searchSql = searchSql.replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "");
		init();
	}
	/**
	 * 
	 * 功能: 初始化，提取参数 
	 * 创建日期:2007-7-18
	 */
	public void init(){
		
		if(request.getParameter("searchSql") != null)
			searchSql = request.getParameter("searchSql");
		if(request.getParameter("perPageCount") != null)
			perPageCount = Integer.parseInt(request.getParameter("perPageCount"));
		if(request.getParameter("totalCount") != null)
			totalCount = Integer.parseInt(request.getParameter("totalCount"));
		if(request.getParameter("currentPageNo") != null)
			currentPageNo = Integer.parseInt(request.getParameter("currentPageNo"));
		logger.info("pageaction=="+request.getParameter("pageaction") != null);
		if(request.getParameter("pageAction") != null && request.getParameter("pageAction").length() > 0)
			pageaction = Integer.parseInt(request.getParameter("pageAction"));
		
		dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
		
		//总记录数
		if(totalCount == 0 && searchSql.length() > 0)
			totalCount();
		//分析页数
		compute();
	}
	/**总记录数*/
	public void totalCount() {
		String sql = "SELECT count(*)COUNT FROM ("+searchSql+")";
		List count = dbo.queryList(sql, null);
		totalCount = Long.parseLong(((Map)count.get(0)).get("COUNT").toString());
		//totalCount
	}
	/**
	 * 
	 * 功能: 计算分页
	 * 作者: nmlhm
	 * 创建日期:2007-7-18
	 */
	public void compute(){
		//pageaction 0：首页 1：上一页 2：下一页 3：尾页 
		
		totalPageCount = (totalCount + perPageCount -1)/perPageCount;
		if(totalPageCount == 0)
			totalPageCount = 1;
		switch(pageaction){
			case 0: currentPageNo = 1; break;
			case 1: currentPageNo -= 1;break;
			case 2: currentPageNo += 1;break;
			case 3: currentPageNo = (int)totalPageCount; break;
			default :;
		}
		if(currentPageNo == 0)
			currentPageNo = 1;
		if(currentPageNo > totalPageCount )
			currentPageNo = (int)totalPageCount;
		query();
	}
	/**
	 * 
	 * 功能: 生成页面显示的分页信息 
	 * 创建日期:2007-7-18
	 * //onclick="javascript:document.getElementById('pageaction').value='next'
	 */
	public void createPageStr(){
		// 当前页/总页数
		String pageIndicator = "| 第" + currentPageNo + "页 | 共"
				+ totalPageCount + "页 ";
		// 首页
		String firstPage = "| <a title=转到首页 class=link-f onClick=\"setCurrentPageNO(1)\" style=cursor:hand>首页</a> ";
		// 处理是否显
		if (totalPageCount < 2) {
			firstPage = "| 首页 ";
		}

		// 尾页
		String lastPage = "| <a title=转到尾页 class=link-f onClick=\"setCurrentPageNO("+totalPageCount+")\" style=cursor:hand>尾页</a> ";
		// 处理是否显示
		if (currentPageNo == totalPageCount) {
			lastPage = "| 尾页 ";
		}

		// previousPage
		String previousPage = "";
		int previousPageCount = 0;
		// 处理页数问题,往上翻最多翻到第一页。不可能为负数
		if (totalPageCount < 2) {
			previousPageCount = 1;
			previousPage = "| 上一页 ";
		} else {
			previousPageCount = currentPageNo - 1;
			previousPage = "| <a title=转到上一页 class=link-f onClick=\"setCurrentPageNO("+previousPageCount+")\" style=cursor:hand>上一页</a> ";
		}

		// nextPage
		String nextPage = "";
		int nextPageCount = 0;
		if ((currentPageNo + 1) > totalPageCount) {
			nextPageCount = Integer.parseInt(totalPageCount+"");
			nextPage = "| 下一页 ";
		} else {
			nextPageCount = currentPageNo + 1;
			nextPage = "| <a title=转到下一页 class=link-f onClick=\"setCurrentPageNO("+nextPageCount+")\" style=cursor:hand>下一页</a> ";
		}

	
		// Jump to
		String jumpTo = "<span>"
				+ "<input type=\"hidden\" name=\"searchSql\" value=\""
				+ searchSql
				+ "\" >"
				+ "| 每页 <input type=\"text\" size=1 class=\"input1\" name=\"perPageCount\" value=\""
				+ (perPageCount)
				+ "\" onKeyPress=\"inputInt();if(event.keyCode==13) submitPageForm()\" maxLength=\"4\"" 
				+" errName='每页记录数' misType= \"string\" misNull=\"1\" errMsg='输入的记录数过大!'"
				+ ">条记录 | 转到"
				//+ "<img style=cursor:hand src=\""
				//+ STYLE_PATH
				//+ "images/go.gif\" align=\"absmiddle\" onclick=\"submitPageForm()\">"
				+ " <input type=\"text\" class=\"input1\" name=\"currentPageNo\" size=1 value='" 
				+ currentPageNo
				+ "' onKeyPress=\"inputInt();if(event.keyCode==13) submitPageForm()\" maxLength=\"9\"" 
				+" errName='转到页数' misType= \"string\" misNull=\"1\" errMsg='输入的页数值过大!'"+
						">页 |<input type=\"button\" onclick=\"submitPageForm();\" value=\"GO\"></span>";

		pageStr= "<form id=\"pageForm\" method=\"POST\" action=\"" + basePath
				+ "\" name=\"pageForm\" >"
				+  "| 共有<font color=red>" + totalCount
				+ "</font>条 " + pageIndicator + firstPage
				+ previousPage + nextPage + lastPage + jumpTo + "<br>"
				+ this.getConditonStr()  + "</form>";
		
//		StringBuffer stu = new StringBuffer("");
//		stu.append("\r\n<form id=\"pageForm\" method=\"POST\" action=\""+basePath+"\" name=\"pageForm\" >\r\n")
//		.append("<input type=hidden  id=\"pageAction\" name=\"pageAction\">\r\n")
//		.append("<br>共有").append(totalCount).append("条&nbsp;&nbsp;&nbsp;&nbsp;第&nbsp;")
//		.append(currentPageNo).append("&nbsp;/&nbsp;").append(totalPageCount).append("&nbsp;页&nbsp;&nbsp;");
//		//是否首页
//		if(currentPageNo == 1)
//			stu.append("首页&nbsp;&nbsp;上一页&nbsp;&nbsp;");
//		else
//			stu.append("<a class=linkbutton onclick=\"skipPage('0');\">首页</a>&nbsp;&nbsp;")
//				.append("<a class=linkbutton onclick=\"skipPage('1');\">上一页</a>&nbsp;&nbsp;");
//		//是否尾页
//		if(currentPageNo == totalPageCount || totalPageCount == 1)
//			stu.append("下一页&nbsp;&nbsp;尾页&nbsp;&nbsp;");
//		else
//			stu.append("<a class=linkbutton onclick=\"skipPage('2');\">下一页</a>&nbsp;&nbsp;")
//			.append("<a class=linkbutton onclick=\"skipPage('3');\">尾页</a>&nbsp;&nbsp;\r\n");
//		
//		stu.append("<span><input type=\"hidden\" name=\"searchSql\" value=\""+searchSql+"\" >每页")
//		   .append("<input class=\"pagetext1\" type=\"text\" id=\"perPageCount\" onkeyup=\"value=value.replace(/[^(\\d.)]/g,'') ;checkRowSize(this);\" size=1 name=\"perPageCount\" value=\""+perPageCount+"\" maxLength=\"3\"")
//		   .append(" onbeforepaste=\"value=value.replace(/[^(\\d.)]/g,'') ;\">条&nbsp;\r\n")
//		   .append("<input type=button  class=\"littlebutton2\" value=转到 id=GOButton onclick=\"checkPageNum();\">&nbsp;第&nbsp;\r\n")
//		   .append("<input class=\"pagetext1\" type=\"text\" id=\"currentPageNo\" name=\"currentPageNo\" size=1 maxLength=\"9\" value=\""+currentPageNo+"\"" )
//		   .append(" onkeyup=\"value=value.replace(/[^(\\d.)]/g,'') ;checkPageNum();\" onbeforepaste=\"value=value.replace(/[^(\\d.)]/g,'') ;\">\r\n")
//		   .append("&nbsp;页 </span><br></form>");
//		//一段脚本,提交，验证
//		stu.append("\r\n<script  LANGUAGE=\"JavaScript\">\r\n")
//		 .append("maxRows = "+totalCount+";\r\n")	
//		 .append("curPageNum = "+currentPageNo+";\r\n")
//		 .append("pageFormObj = document.getElementById('pageForm');\r\n")
//		 .append("function skipPage(action){\r\n")
//		 .append("document.getElementById('pageAction').value=action;\r\n")
//		 .append("pageFormObj.submit();\r\n")
//		 .append("}\r\n")
//		 .append("function checkRowSize(obj){\r\n")			
//		 .append("if(parseInt(obj.value) > maxRows){\r\n")
//		 .append("alert('记录数太大，请重新输入！');\r\n")
//		 .append("if(maxRows > 0)\r\n")
//		 .append("obj.value=maxRows;\r\n")	
//		 .append("}\r\n")
//		 .append("if(event.keyCode == 13)\r\n")
//		 .append("checkPageNum(document.getElementById('currentPageNo'));\r\n")
//		 .append("}\r\n")
//		 .append("function checkPageNum(){\r\n")
//		 .append("obj = document.getElementById('currentPageNo');\r\n")
//		 .append("maxPage = "+totalPageCount+";\r\n")
//		 .append("rowsnum = 0;\r\n")
//		 .append("rowsize = document.getElementById('perPageCount').value;\r\n")
//		 .append("if(!isNaN(rowsize));\r\n rowsnum = parseInt(rowsize);\r\n")
//		 .append("multiplyCount = parseInt(obj.value) * rowsnum;\r\n")
//		 .append("if(Math.floor(maxRows/rowsnum+1) < parseInt(obj.value) || (maxRows == rowsnum && parseInt(obj.value) > 1)){\r\n")
//		 .append("alert('页数太大，请重新输入！');\r\n")
//		 .append("obj.value=Math.floor(maxRows/rowsnum+1);\r\n")
//		 .append("if(maxRows == rowsnum)obj.value=1;\r\n")
//		 .append("return;\r\n")
//		 .append("}\r\n")		 
//		 .append("if(event.keyCode == 13 || event.srcElement.id == 'GOButton')\r\n")
//		 .append("submitPageForm();\r\n")
//		 .append("}\r\n")
//		 .append("function submitPageForm(){\r\n")
//		 .append("if(document.getElementById('currentPageNo').value.length > 0)\r\n")
//		 .append("pageFormObj.submit();\r\n")
//		 .append("}\r\n")
//		.append("</script>");
//		pageStr = stu.toString();
//		
		
		
		
	}
	/**
	 * 功能: 分页查询
	 * 作者: Lihuiming
	 * 创建日期:2007-7-18
	 * @param sql
	 * @param params
	 * @return
	 */
	public void query(){
		//SELECT * FROM (SELECT temp.* ,ROWNUM num FROM (sql ) temp where ROWNUM <= 10 ) WHERE　num > 0
		
		// 结果集范围		
		int min = (currentPageNo -1 ) * perPageCount +1;
		int max = min + perPageCount-1;
		String sql = "SELECT * FROM (SELECT temp.* ,ROWNUM num FROM ( "+ searchSql+") temp " 
					+"where ROWNUM <= " + max + " ) where num >= "+min;
		logger.debug("SQL=="+sql);
		dataList = dbo.queryList(sql ,null);
		
		createPageStr();
	}
	
	
	
	private HttpServletRequest request;
	DBMgr dbo = null;
	
	List dataList = new ArrayList();
	/**   当前页数码 */
	private int currentPageNo = 1;
	/** 请求动作 下一页1, 上一页2 , 首页 0 ,最后一页 3*/
	private int pageaction = 4;
	/** 总记录数*/
	private long totalCount = 0;
	/**  每页记录数，默认为10条记录 */
	private int perPageCount = 15;
	/** 总页数*/
	private long totalPageCount  = 0;
	/**  页面查询条件的完成的sql语句 */
	private String searchSql = "";
	/**  基本的路径  */
	private String basePath = "";
	/**页面显示的html代码*/
	private String pageStr = "";
//	
	/**
	 * 功能:取得参数
	 * 作者: 谢彬
	 * 创建日期:Mar 14, 2008
	 * @return
	 */
	private String getConditonStr(){
		String conditionStr="";
		Set set=conditionMap.keySet();
		for (Iterator iter = set.iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			conditionStr+="<input type=\"hidden\" name=\""+name+"\" value=\""+conditionMap.get(name)+"\">";
		}
		return conditionStr;
		
	}
	
	
	public String getBasePath() {
		return basePath;
	}
	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}	
	public void setPerPageCount(int perPageCount) {
		this.perPageCount = perPageCount;
	}
	public String getSearchSql() {
		return searchSql;
	}
	public void setSearchSql(String searchSql) {
		this.searchSql = searchSql;
	}

	public List getDataList() {
		return dataList;
	}
	public String getPageStr() {
		return pageStr;
	}


	/**
	 * @return Returns the conditionMap.
	 */
	public Map getConditionMap() {
		return conditionMap;
	}

	/**
	 * 给这个对象的hashtable中添加需要传递的查询条件。
	 * 功能:
	 * 作者: shaokun305
	 * 创建日期:Mar 8, 2006
	 * @param key
	 * @param obj
	 * @return
	 */
	public void pushCondition(String key, Object obj) {
		this.conditionMap.put(key, obj);
		

	}

	public int getCurrentPageNo() {
		return currentPageNo;
	}

	public void setCurrentPageNo(int currentPageNo) {
		this.currentPageNo = currentPageNo;
	}

	public int getPerPageCount() {
		return perPageCount;
	}
}
